package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/authorInfo")
public class AuthorInfoServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 通过这个方法，来获取到指定的博客作者信息
        String blogId = req.getParameter("blogId");
        if(blogId == null || "".equals(blogId)){
            // 参数绝少
            resp.getWriter().write("{ \"ok\": false,\"reason\": \"参数缺失！\"}");
            return;
        }
        // 根据 blogId 在数据库中进行查找，找到对应的 Blog 对象
        // 然后，在进一步根据 Blog 对象 找到作者信息
        Blog blog = BlogDao.selectOne(Integer.parseInt(blogId));
        if(blog == null){
            resp.getWriter().write("{ \"ok\": false,\"reason\": \"要查找的博客不存在！\"}");
            return;
        }
        //根据 blog 对象，查询到用户对象
        User author = UserDao.selectById(blog.getUserId());
        if (author == null){
            resp.getWriter().write("{ \"ok\": false,\"reason\": \"要查找的用户不存在！\"}");
            return;
        }
        // 把 author 对象返回到浏览器这边
        author.setPassword("");
        String respJson = objectMapper.writeValueAsString(author);
        resp.getWriter().write(respJson);
    }
}
